package com.qipay.cpchannel.service.impl;

import com.qipay.baas.model.Cp;
import com.qipay.baas.model.CpChannel;
import com.qipay.cp.CpService;
import com.qipay.cpchannel.service.CpChannelService;
import com.qipay.mapper.CpChannelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CpChannelServiceImpl implements CpChannelService {
    @Autowired
    CpChannelMapper cpChannelMapper;

    @Autowired
    CpService cpService;

    @Override
    public CpChannel get(long id) {
        return cpChannelMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int updateState(long id, byte state) {
        CpChannel cpChannel = new CpChannel();
        cpChannel.setId(id);
        cpChannel.setState(state);
        cpChannelMapper.updateByPrimaryKeySelective(cpChannel);

        //clean proxy`s cp state.
        cpChannel = get(id);
        return updateChildCpState(cpChannel.getCpId(), cpChannel.getChannelType(), state);
    }

    @Override
    @Transactional
    public int insert(CpChannel cpChannel) {
        return cpChannelMapper.insert(cpChannel);
    }

    @Override
    @Transactional
    public int update(CpChannel cpChannel) {
        return cpChannelMapper.updateByPrimaryKey(cpChannel);
    }

    @Override
    @Transactional
    public int delete(long id) {
        return cpChannelMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<CpChannel> selectByCpId(long cpid, int p, int pz) {
        p = p <= 0 ? 1 : p;
        pz = pz <= 0 ? 10 : pz;
        return cpChannelMapper.selectByCpId(cpid, (p - 1) * pz, pz);
    }

    @Override
    public long countByCpId(long cpId) {
        return cpChannelMapper.countByCpId(cpId);
    }

    @Override
    @Transactional
    public CpChannel getByCpIdAndChannelType(Long cpId, Byte type) {
        return cpChannelMapper.selectByCpIdAndType(cpId, type);
    }

    @Override
    public CpChannel getAgentChannel(CpChannel childChannel) {
        if (childChannel == null) {
            return null;
        }

        Cp childCp = cpService.getOneById(childChannel.getCpId());
        if (childCp == null || childCp.getAgentId() == 0) {
            return null;
        }

        Long agentId = childCp.getAgentId();
        CpChannel agentChannel = getByCpIdAndChannelType(agentId, childChannel.getChannelType());
        return agentChannel;
    }

    @Override
    public int updateChildCpState(long agentId, byte channelType, byte state) {
        if (agentId > 0) {
            return cpChannelMapper.updateChildState(agentId, channelType, state);
        }
        return 0;
    }
}
